package com.kf.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.kf.aop.LogOperation;
import com.kf.config.RedisUtil;
import com.kf.mapper.RoleMapper;
import com.kf.pojo.Role;
import com.kf.pojo.form.RoleForm;
import com.kf.service.RoleService;
import com.kf.util.R;
import com.kf.util.ResultCode;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.constraints.Pattern;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 康峰
 * @since 2022-10-17
 */
@RestController
@RequestMapping("/role")
@Api("角色")
public class RoleController {

    @Resource
    private RoleService roleService;
    @Resource
    RedisUtil redisUtil;
    @Resource
    private RoleMapper roleMapper;

    @DeleteMapping("/ceshi")
    @ApiOperation("测试删除角色，看角色权限表和用户角色表会不会跟着删除")
    public R delete(@Pattern(regexp = "",message = "只能填入数字") @RequestParam("id") int id){

        try {
            QueryWrapper<Role> roleQueryWrapper = new QueryWrapper<>();
            roleQueryWrapper.eq("id",id);
            roleService.remove(roleQueryWrapper);

        }catch (Exception e){
            return  R.okey(ResultCode.ROLE_DELETE_ERROR);
        }
        return  R.okey(ResultCode.SUCCESS);
    }

    @PostMapping("/addRole")
    @ApiOperation("添加角色")
    @LogOperation("添加角色")
    public R addRole(@Validated @RequestBody RoleForm roleForm){
        try {
            Role role = new Role();
            role.setName(roleForm.getName());
            role.setRemark(roleForm.getRemark());
            QueryWrapper<Role> roleQueryWrapper = new QueryWrapper<>();
            roleQueryWrapper.eq("name",roleForm.getName());
            Role role1 = roleMapper.selectOne(roleQueryWrapper);
            if(role1!=null){
                return R.okey(ResultCode.ROLE_ADD_ERROR1);
            }
            roleService.addRole(role);
        redisUtil.deleteByPrex("role:current:*");
        return R.okey(ResultCode.SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return R.error(ResultCode.ROLE_ADD_ERROR);
        }
    }

}

